﻿using System;
using System.Linq;
using System.Web.Services;
using Dost.Khcn.Biz;
using Dost.Khcn.Web.Common;

namespace Dost.Khcn.Web.DanhMuc.LinhVuc
{
    public partial class NhomLinhVuc : System.Web.UI.Page
    {
        #region Properites

        private static LinhVucBiz _linhVucBiz;
        private static LinhVucBiz LinhVucManager
        {
            get { return _linhVucBiz ?? (_linhVucBiz = new LinhVucBiz()); }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!WebCommon.CurrrentEmployee.IsAdmin)
            {
                Response.Redirect("~/NoPermission.aspx");
            }
        }

        #region Web methods

        [WebMethod(EnableSession = true)]
        public static object GetAll()
        {
            var nhomLinhvucs = LinhVucManager.GetAllNhomLinhVucs();
            nhomLinhvucs.Insert(0, new Data.EntityModel.NhomLinhVuc { Id = 0, Ten = string.Empty });

            return nhomLinhvucs.Select(x => new { x.Id, x.MaTen });
        }

        [WebMethod(EnableSession = true)]
        public static object NhomLinhVucList(int jtStartIndex, int jtPageSize, string jtSorting, string name, string code)
        {
            return LinhVucManager.GetNhomLinhVucs(jtStartIndex, jtPageSize, jtSorting, name, code);
        }

        [WebMethod(EnableSession = true)]
        public static object Create(Data.EntityModel.NhomLinhVuc record)
        {
            try
            {
                var addedRecord = LinhVucManager.CreateNhomLinhVuc(record);
                return new { Result = "OK", Record = addedRecord };
            }
            catch (ApplicationException appEx)
            {
                var data = appEx.Message == "CodeIsExisted" ? record.Ma : record.Ten;
                return new { Result = "ERROR", Message = string.Format(WebCommon.GetGlobalString(appEx.Message), data) };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object Delete(int Id)
        {
            return LinhVucManager.DeleteNhomLinhVuc(Id);
        }

        [WebMethod(EnableSession = true)]
        public static object Update(Data.EntityModel.NhomLinhVuc record)
        {
            try
            {
                LinhVucManager.UpdateNhomLinhVuc(record);
                return new { Result = "OK" };
            }
            catch (ApplicationException appEx)
            {
                var data = appEx.Message == "CodeIsExisted" ? record.Ma : record.Ten;
                return new { Result = "ERROR", Message = string.Format(WebCommon.GetGlobalString(appEx.Message), data) };
            }
        }

        #endregion
    }
}